package com.group6.blogplatform.web.admin;

import com.group6.blogplatform.Bean.User;
import com.group6.blogplatform.service.inter.UserService;
import com.group6.blogplatform.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/admin")
public class registController {

    @Autowired
    private UserService userService;

    @GetMapping("/regist")
    public String registPage(){
        return "admin/regist";
    }

    @PostMapping("/register")
    public String regist( String username,
                          String nickname,
                          String email,
                          String password,
                          HttpSession session,
                          RedirectAttributes attributes) {
        User user = userService.checkUser(username, password);
        if (user == null) {
            user = new User();
            user.setUsername(username);
            user.setAdmin(false);
            user.setEmail(email);
            user.setPassword(MD5Utils.code(password));
            user.setNickname(nickname);
            userService.addUser(user);
            session.setAttribute("user", user);
            return "admin/index";
        }else{
            attributes.addFlashAttribute("message", "用户已存在");
            System.out.println("error");
            return "redirect:/admin/regist";
        }
    }
}
